﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;

class DelayedInterpolationManager
{
    private List<Vector3> positions = new List<Vector3>(2);
    private List<Quaternion> rotations = new List<Quaternion>(2);
    private List<DateTime> updateTimes = new List<DateTime>(2);

    Transform transform;
    public DelayedInterpolationManager(Transform transform)
    {
        this.transform = transform;
    }

    public void DelayInterpolateMovement()
    {
        if (updateTimes.Count >= 2)
        {
            float updateDelta = (float)(updateTimes[1] - updateTimes[0]).TotalMilliseconds;
            if (updateDelta > 90) updateDelta = 90;

            float currentDelta = (float)(DateTime.Now - updateTimes[1]).TotalMilliseconds;
            float travelRatio = currentDelta / updateDelta;
            this.transform.position = Vector3.Lerp(positions[0], positions[1], travelRatio);
            this.transform.rotation = rotations[1];
        }
    }

    public void ReadSerializedData(BitStream stream) 
    {
        Vector3 location = this.transform.position;
        Quaternion orientation = this.transform.rotation;
        stream.Serialize(ref location);
        stream.Serialize(ref orientation);

        if (updateTimes.Count >= 2) updateTimes.RemoveAt(0);
        if (positions.Count >= 2) positions.RemoveAt(0);
        if (rotations.Count >= 2) rotations.RemoveAt(0);

        updateTimes.Add(DateTime.Now);
        positions.Add(location);
        rotations.Add(orientation);
    }

    public void WriteSerializedData(BitStream stream)
    {
        Vector3 location = this.transform.position;
        Quaternion orientation = this.transform.rotation;
        stream.Serialize(ref location);
        stream.Serialize(ref orientation);
    }
}
